package com.liming.shop.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liming.common.exception.BusinessException;
import com.liming.common.pojo.dto.shop.ShopAddOrUpdateDTO;
import com.liming.common.pojo.dto.shop.ShopPageQuery;
import com.liming.common.pojo.entity.shop.Shop;
import com.liming.common.pojo.vo.PageVO;
import com.liming.common.pojo.vo.shop.ShopVO;
import com.liming.common.util.PageUtils;
import com.liming.common.util.mybatisplus.MPUtil;
import com.liming.shop.mapper.ShopMircoMapper;
import com.liming.shop.service.ShopMircoService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author liming
 * @date 2025/3/9
 */
@Service
@AllArgsConstructor
public class ShopMircoServiceImpl extends ServiceImpl<ShopMircoMapper, Shop> implements ShopMircoService, MPUtil<Shop> {

    @Override
    public PageVO<ShopVO> pageShop(ShopPageQuery query) {
        IPage<Shop> rawPage = lambdaQuery()
                .like(StrUtil.isNotBlank(query.getName()), Shop::getName, query.getName())
                .eq(StrUtil.isNotBlank(query.getProvince()), Shop::getProvince, query.getProvince())
                .eq(StrUtil.isNotBlank(query.getCity()), Shop::getCity, query.getCity())
                .eq(StrUtil.isNotBlank(query.getDistrict()), Shop::getDistrict, query.getDistrict())
                .eq(StrUtil.isNotBlank(query.getStreet()), Shop::getStreet, query.getStreet())
                .page(setPage(query));
        return PageUtils.convert(rawPage, shop -> {
            ShopVO vo = new ShopVO();
            BeanUtils.copyProperties(shop, vo);
            return vo;
        });
    }

    @Override
    public Boolean saveShop(ShopAddOrUpdateDTO dto) {
        Shop save = new Shop();
        BeanUtils.copyProperties(dto, save);
        Assert.isTrue(save(save), () -> new BusinessException("商店保存失败"));
        return true;
    }

    @Override
    public Boolean updateShop(ShopAddOrUpdateDTO dto) {
        Assert.notNull(dto.getId(), () -> new BusinessException("商店ID不能为空"));
        Shop update = new Shop();
        BeanUtils.copyProperties(dto, update);
        Assert.isTrue(updateById(update), () -> new BusinessException("更新商店信息失败"));
        return true;
    }

    @Override
    public String pickupPointInfoById(Long pickupPointId) {
        Shop shop = lambdaQuery().eq(Shop::getId, pickupPointId).one();
        Assert.notNull(shop, () -> new BusinessException("店铺不存在"));
        return shop.getName() + "/" +
                shop.getContactPhone() + "/" +
                shop.getProvince() + shop.getCity() + shop.getDistrict() + shop.getStreet() + shop.getAddress();
    }
}
